package com.qf.listener;


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: RepeatPurchasesListener
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/8/15 21:05
 */

@Component
public class RepeatPurchasesListener {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener
    public void recerverMessage(Message message, Channel channel,Object msg) throws Exception{
       String id= (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(id, 0);
        if (isLock){
            redisTemplate.opsForValue().set(id,0,1, TimeUnit.SECONDS);
            System.out.println("保存订单");
            System.out.println("保存订单详情");
            redisTemplate.opsForValue().set(id,1);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }else {
            Integer value = (Integer) redisTemplate.opsForValue().get(id);
            if ("1".equals(value)){
                System.out.println("帮助应答");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        }
    }
}
